cmake_minimum_required(VERSION 3.22)

project(CMakeRookie VERSION 0.1)

set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_INSTALL_PREFIX sandbox)

option(USE_MYMATH "Use tutorial provided math implementation" ON)
configure_file(CMakeRookieConfig.h.in CMakeRookieConfig.h)

if(USE_MYMATH)
    add_subdirectory(mathfunctions)
    list(APPEND EXTRA_LIBS MathFunctions)
endif()

add_executable(CMakeRookie tutorial.cxx)
target_link_libraries(CMakeRookie PUBLIC ${EXTRA_LIBS})
target_include_directories(CMakeRookie PUBLIC
        "${PROJECT_BINARY_DIR}"
        )

install(TARGETS CMakeRookie DESTINATION bin)
install(FILES "${PROJECT_BINARY_DIR}/CMakeRookieConfig.h"
        DESTINATION include
        )

# support search dynamic lib from relative install path
set(CMAKE_BUILD_WITH_INSTALL_RPATH True)
set_target_properties(CMakeRookie PROPERTIES INSTALL_RPATH $ORIGIN/../lib)

enable_testing()
add_test(NAME Runs COMMAND CMakeRookie 25)
add_test(NAME Usage COMMAND CMakeRookie)
set_tests_properties(Usage
        PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
        )
# define a function to simplify adding tests
function(do_test target arg result)
    add_test(NAME Comp${arg} COMMAND ${target} ${arg})
    set_tests_properties(Comp${arg}
            PROPERTIES PASS_REGULAR_EXPRESSION ${result}
            )
endfunction()
# do a bunch of result based tests
do_test(CMakeRookie 4 "4 is 2")
do_test(CMakeRookie 9 "9 is 3")
do_test(CMakeRookie 5 "5 is 2.236")
do_test(CMakeRookie 7 "7 is 2.645")
do_test(CMakeRookie 25 "25 is 5")
do_test(CMakeRookie -25 "-25 is (-nan|nan|0)")
do_test(CMakeRookie 0.0001 "0.0001 is 0.01")